<?php

namespace app\http\controller\admin\sys\auth;

use mon\env\Config;
use app\model\AdminModel;
use app\model\AuthGroupModel;
use app\model\AuthAccessModel;
use app\http\controller\admin\Controller;

/**
 * 角色组别
 */
class GroupController extends Controller
{
    /**
     * 角色组管理
     *
     * @return string
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            return $this->success('ok', AuthGroupModel::instance()->getGroupTree());
        };
        // 获取新增角色组别权限
        $add = $this->auth->check('/admin/sys/auth/group/add', $this->userInfo['id']);
        $this->assign('add', $add);
        $this->assign('supperGroup', json_encode(Config::instance()->get('admin.supper_group'), JSON_UNESCAPED_UNICODE));
        return $this->fetch('sys/auth/group/index');
    }

    /**
     * 新增组别
     *
     * @return string
     */
    public function add(AuthGroupModel $model)
    {
        if ($this->request->isPost()) {
            // 新增操作
            $data = $this->request->post();
            $add = $model->add($data);
            if (!$add) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }

        $this->assign('groups', $model->getGroupTree(true));
        return $this->fetch('sys/auth/group/add');
    }

    /**
     * 编辑组别
     *
     * @return string
     */
    public function edit(AuthGroupModel $model)
    {
        $idx = $this->request->get('idx');
        if (in_array($idx, Config::instance()->get('admin.supper_group', []))) {
            return $this->error('不允许操作超级管理员组别');
        }
        $info = $model->getInfo(['id' => $idx]);
        if (!$info) {
            return $this->error($model->getError());
        }

        if ($this->request->isPost()) {
            // 编辑操作
            $data = $this->request->post();
            $data['idx'] = $idx;
            $edit = $model->edit($data);
            if (!$edit) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }

        // 获取组别数据，并移除自己及后代节点
        $baseGroups = $model->getGroupTree(true);
        // 获取自己及后代的节点id
        $childrenIds = $this->container->tree->data($baseGroups)->getChildrenIds($info['id'], true);
        // 移除自己及后代的节点
        $groups = [];
        foreach ($baseGroups as $item) {
            if (!in_array($item['id'], $childrenIds)) {
                $groups[] = $item;
            }
        }

        $this->assign('groups', $groups);
        $this->assign('data', $info);
        return $this->fetch('sys/auth/group/edit');
    }

    /**
     * 获取用户组下所有权限
     *
     * @return string
     */
    public function role(AuthGroupModel $model)
    {
        // 自身ID
        $id = $this->request->post("id", 0);
        // 父级ID
        $pid = $this->request->post("pid", 0);
        // 获取数据
        $data = $model->getRoleTree($id, $pid);
        if ($data === false) {
            return $this->error($model->getError());
        }

        return $this->success('ok', $data);
    }

    /**
     * 获取角色组别用户列表
     *
     * @return string
     */
    public function user(AdminModel $adminModel)
    {
        $option = $this->request->get();
        if (!isset($option['gid']) || !is_numeric($option['gid']) || !is_int($option['gid'] + 0) || $option['gid'] < 1) {
            return $this->success('ok', [], ['count' => 0]);
        }
        // $option['status'] = 1;
        $result = $adminModel->queryList($option, true);
        return $this->success('ok', $result['list'], ['count' => $result['total']]);
    }

    /**
     * 获取未关联指定组别的用户列表
     *
     * @param AdminModel $adminModel
     * @return string
     */
    public function getAccessUser(AdminModel $adminModel)
    {
        $gid = $this->request->post("gid", 0);
        $sql = "SELECT
                    a.id,
                    a.username 
                FROM
                    mon_admin AS a
                    LEFT JOIN auth_access AS b ON a.id = b.uid
                    LEFT JOIN auth_group AS c ON b.group_id = c.id 
                WHERE
                    b.group_id <> ? 
                GROUP BY
                    b.uid
                HAVING
                    b.uid NOT IN ( SELECT uid FROM auth_access WHERE group_id = ? ) ";

        $data = $adminModel->query($sql, [$gid, $gid]);

        return $this->success('ok', $data);
    }

    /**
     * 关联角色组别用户
     *
     * @param AuthGroupModel $model
     * @param AuthAccessModel $access
     * @return string
     */
    public function bindUser(AuthGroupModel $model, AuthAccessModel $access)
    {
        $idx = $this->request->get('idx');
        if (in_array($idx, Config::instance()->get('admin.supper_group', []))) {
            return $this->error('不允许操作超级管理员组别');
        }
        $info = $model->getInfo(['id' => $idx]);
        if (!$info) {
            return $this->error($model->getError());
        }

        if ($this->request->isPost()) {
            $option = $this->request->post();
            $option['idx'] = $idx;
            $save = $access->bindUsers($option);
            if (!$save) {
                return $this->error($access->getError());
            }

            return $this->success('操作成功');
        }

        // 获取所有可选用户id, username
        $field = 'id as value, username as title';
        $users = AdminModel::instance()->field($field)->whereNotIn('id', Config::instance()->get('admin.supper_admin', []))->select();
        // 获取所有已绑定关联的用户id
        $selects = $access->field('uid')->where('group_id', $idx)->select();
        $selectUsers = [];
        foreach ($selects as $item) {
            $selectUsers[] = $item['uid'];
        }
        $data = [
            'idx'       => $idx,
            'users'     => $users,
            'selects'   => $selectUsers
        ];
        $this->assign('data', json_encode($data, JSON_UNESCAPED_UNICODE));
        return $this->fetch('sys/auth/group/bindUser');
    }

    /**
     * 解除角色组别关联用户绑定
     *
     * @return string
     */
    public function unbindUser()
    {
        $option = $this->request->post();
        $model = $this->auth->model('access');
        $save = $model->unbind($option);
        if (!$save) {
            return $this->error($model->getError());
        }

        return $this->success('操作成功');
    }
}
